package biz

import (
	"context"
	"fmt"
	"manage/api/class"
	"manage/api/user"
	"strings"

	rp "github.com/Fromsko/gouitls/reply"
	"github.com/gin-gonic/gin"
)

// StudentClass 定义学生班级关联结构体
type StudentClass struct {
	StudentID string `gorm:"column:student_id" json:"student_id"`
	ClassID   string `gorm:"column:class_id" json:"class_id"`
	UserName  string `gorm:"column:username" json:"username"`
}

// JoinClassRequest 请求格式
type JoinClassRequest struct {
	StudentID string `json:"student_id"`
	ClassID   string `json:"class_id"`
	UserName  string `gorm:"column:username" json:"username"`
}

// JoinClassResponse 响应格式
type JoinClassResponse struct {
	Message string `json:"message"`
}

// LeaveClassRequest 请求格式
type LeaveClassRequest struct {
	StudentID string `json:"student_id"`
	ClassID   string `json:"class_id"`
}

// LeaveClassResponse 响应格式
type LeaveClassResponse struct {
	Message string `json:"message"`
}

func (u *APIUseCase) Student() *Method {
	return &Method{
		Post: func(c *gin.Context) {
			classId := c.Param("class_id")
			studentId := c.PostForm("student_id")
			hasUser := ""
			username := ""

			if studentId == "" {
				rp.Failed(c, "加入失败", "参数不正确")
				return
			}

			checkExistence := func(classId, studentId string, hasUser *string) bool {
				flag := true

				u.Repo.User(func(ctx context.Context, usc user.UserServiceClient) {
					req := &user.GetUserRequest{UserId: studentId}
					if resp, _ := usc.GetUser(ctx, req); resp.Code == 400 {
						flag = false
						*hasUser = strings.Split(resp.Msg, ":")[1]
					} else {
						username = resp.Data.Username
					}
				})

				if !flag {
					return false
				}

				u.Repo.Class(func(ctx context.Context, csc class.ClassServiceClient) {
					req := &class.GetClassRequest{ClassId: classId}
					if resp, _ := csc.GetClass(ctx, req); resp.Code == 400 {
						flag = false
						fmt.Println(resp.Msg, resp.Code, resp.ClassInfo)
						*hasUser = strings.Split(resp.Msg, ":")[1]
					}
				})

				return flag
			}

			if !checkExistence(classId, studentId, &hasUser) && hasUser != "" {
				rp.Failed(c, "加入失败", hasUser)
				return
			}

			// 加入班级
			{
				reply, err := u.Repo.JoinClass(&JoinClassRequest{
					StudentID: studentId,
					ClassID:   classId,
					UserName:  username,
				})

				if err != nil {
					rp.Failed(c, "加入失败", err.Error())
					return
				}

				rp.Succeed(c, reply.Message)
			}
		},

		Delete: func(c *gin.Context) {

			classId := c.Param("class_id")
			studentId := c.PostForm("student_id")

			if studentId == "" {
				rp.Failed(c, "删除失败", "参数不正确")
				return
			}

			reply, err := u.Repo.LeaveClass(&LeaveClassRequest{
				StudentID: studentId,
				ClassID:   classId,
			})

			if err != nil {
				rp.Failed(c, "离开失败", err.Error())
				return
			}

			rp.Succeed(c, reply.Message)
		},
	}
}
